package com.ffzx.parentweb.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 用于跳过cas过虑器，直接访问到controller
 * 初始化参数noCasUrl的值如：/500.do,/help/test/   多个使用“逗号”隔开
 * 需要配置在cas过虑器之前
 * 
 * @author CMM
 *
 * 2016年6月29日 下午3:23:22
 */
public class SkipCasFilter implements Filter {
	
	/*
	 * 需要跳过cas过虑器的URL集合
	 */
	private String[] urlArray;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String noCasUrl = filterConfig.getInitParameter("noCasUrl");
		if(null != noCasUrl){
			urlArray = noCasUrl.split(",");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(null == urlArray || urlArray.length < 1){
			chain.doFilter(request, response);
			return ;
		}
		
		boolean isCasUrl = true;
		for(String url : urlArray){
			HttpServletRequest httpServletRequest = (HttpServletRequest)request;  
			String servletPath = httpServletRequest.getServletPath();//如：/help/test/listDemo.do
			//String requestUri = httpServletRequest.getRequestURI();//如：/pms-web/help/test/listDemo.do
			String queryString = httpServletRequest.getQueryString();//如：userName=test
			
			if(servletPath.startsWith(url.trim())){
				isCasUrl = false;
				//跳过后面的过滤器，直接请求servlet  
				String forwardUrl = servletPath;
				if(null != queryString){
					forwardUrl = forwardUrl+ "?" + queryString;
				}
				request.getRequestDispatcher(forwardUrl).forward(request, response); 
				return ;
			}
		}
		
		if(isCasUrl){
			chain.doFilter(request, response);
			return ;
		}
	}

	@Override
	public void destroy() {
		// NO-OP
	}

}
